<template>
  <avue-form ref="form" v-model="form" :option="option" class="maxtrix-design-form">
    <template slot="formatterCfg" slot-scope="{ size }">
      <span>
        <span v-if="form.formatterCfg.type === 'auto'" class="pr-4">自动</span>
        <span v-else-if="form.formatterCfg.type === 'value'" class="pr-4">数值</span>
        <span v-else-if="form.formatterCfg.type === 'percent'" class="pr-4">百分比</span>
      </span>
      <FieldFormatBtn :size="size" @change="onFormatChange" />
    </template>
    <template slot="filters" slot-scope="{ size }">
      <FieldFilterForm :size="size" :value="form.filters" :dimensions="filterDimensions" @change="onFilterChange" />
    </template>
    <template slot="groupBasicHeader" slot-scope="{ column }">
      <svg-icon icon-class="wave-square-rounded" />
      <span>{{ column.label }}</span>
    </template>
    <template slot="groupDimensionHeader" slot-scope="{ column }">
      <svg-icon icon-class="wave-square-rounded" />
      <span>{{ column.label }}</span>
    </template>
    <template slot="groupFilterHeader" slot-scope="{ column }">
      <svg-icon icon-class="wave-square-rounded" />
      <span>{{ column.label }}</span>
    </template>
    <template slot="groupDatetimeHeader" slot-scope="{ column }">
      <svg-icon icon-class="wave-square-rounded" />
      <span>{{ column.label }}</span>
    </template>
  </avue-form>
</template>
<script>
import { requestMatrixOriginGet } from '@/api/chart/origin'
import { getDatasetFieldListFromDE } from '@/api/dataset/dataset'
import FieldFormatBtn from './form/field-format-btn'
import FieldFilterForm from './form/field-filter-table'

const COMPARE_TYPE_DICT = [
  { label: '年环比', value: 'year_mom' },
  { label: '月环比', value: 'month_mom' },
  { label: '日环比', value: 'day_mom' },
  { label: '年同比', value: 'year_yoy' },
  { label: '月同比', value: 'month_yoy' },
]

const INIT_FORM = () => ({
  cate: 'BI',
  tableId: '',
  field: '',
  formatterCfg: {},
  dimension: [],
  filters: [],
})

export default {
  name: 'ChartDesignForm',
  components: { FieldFormatBtn, FieldFilterForm },
  props: {
    visible: { type: Boolean, default: false },
    chart: { type: Object, default: () => ({}) },
  },
  data() {
    return {
      form: INIT_FORM(),
      option: {
        labelSuffix: ' ', // 标题后缀, 默认为空。注意这里写空字符串会不生效，只能写成空格来表示没有
        menuBtn: false,
        detail: false,
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '指标类型',
            prop: 'cate',
            type: 'radio',
            dicData: [
              { label: '基础指标', value: 'BI' },
              { label: '衍生指标', value: 'DI' },
            ],
            span: 24,
            rules: [{ required: true, message: '请选择指标类型', trigger: ['blur', 'change'] }],
            control: (val, form) => {
              return {
                tableId: { disabled: val === 'DI' },
                field: { disabled: val === 'DI' },
                fromChartId: { display: val === 'DI' },
                compareType: { display: val === 'DI' },
              }
            },
          },
        ],
        group: [
          {
            label: '指标设置',
            prop: 'groupBasic',
            column: [
              {
                label: '数据模型',
                prop: 'tableId',
                type: 'cascader',
                dataType: 'string',
                emitPath: false,
                expandTrigger: 'click',
                dicUrl: '/authModel/queryAuthModel',
                dicMethod: 'post',
                dicQuery: { modelType: 'dataset' },
                span: 12,
                rules: [{ required: true, message: '请选择数据模型', trigger: ['blur', 'change'] }],
                props: { label: 'name', value: 'id' },
                change: this.onTableIdChange,
                disabled: false,
              },
              {
                label: '指标字段',
                prop: 'field',
                type: 'select',
                dicData: [],
                span: 12,
                rules: [{ required: true, message: '请选择指标字段' }],
                props: { label: 'name', value: 'id' },
                disabled: false,
              },
              {
                label: '派生于',
                prop: 'fromChartId',
                type: 'select',
                dicUrl: '/jtx/index/list',
                dicMethod: 'post',
                dicQuery: {
                  status: '已探源',
                },
                span: 12,
                rules: [{ required: true, message: '请选择基础指标' }],
                props: { label: 'name', value: 'id' },
                change: this.onFromChartChange,
                display: false,
              },
              {
                label: '衍生类型',
                prop: 'compareType',
                type: 'select',
                dicData: COMPARE_TYPE_DICT,
                span: 12,
                display: false,
              },
              {
                label: '聚合方式',
                prop: 'summary',
                type: 'select',
                dicData: [
                  { label: '求和', value: 'sum' },
                  { label: '平均', value: 'avg' },
                  { label: '最大值', value: 'max' },
                  { label: '最小值', value: 'min' },
                  { label: '标准差', value: 'stddev_pop' },
                  { label: '方差', value: 'var_pop' },
                  { label: '计数', value: 'count' },
                  { label: '去重计数', value: 'uniq_count' },
                ],
                span: 12,
              },
              {
                label: '数值格式',
                prop: 'formatterCfg',
                slot: true,
                span: 12,
              },
            ],
          },
          {
            label: '维度',
            prop: 'groupDimension',
            column: [
              {
                label: '数据中表示细分维度的列',
                labelPosition: 'top',
                prop: 'dimension',
                type: 'select',
                multiple: true,
                filterable: true,
                dicData: [],
                rules: [{ required: true, message: '请选择维度' }],
                props: { label: 'name', value: 'id' },
                span: 24,
              },
            ],
          },
          {
            label: '筛选',
            prop: 'groupFilter',
            column: [
              {
                label: '',
                labelWidth: 0,
                prop: 'filters',
                formslot: true,
                span: 24,
              },
            ],
          },
          {
            label: '日期&时间',
            prop: 'groupDatetime',
            column: [
              {
                label: '时间维度',
                labelTip: '数据中表示如何展示历史数据时间的列',
                labelPosition: 'top',
                prop: 'dateDimension',
                type: 'select',
                dicData: [],
                props: { label: 'name', value: 'id' },
                span: 24,
              },
              {
                label: '时间粒度',
                labelTip: '细分指标值的时间粒度',
                labelPosition: 'top',
                prop: 'dateStyle',
                type: 'select',
                dicData: [
                  { value: 'y', label: '年' },
                  { value: 'y_M', label: '年月' },
                  { value: 'y_Q', label: '年季度' }, // 没有同环比
                  { value: 'y_W', label: '年周' }, // 没有同环比
                  { value: 'y_M_d', label: '年月日' },
                  { value: 'H_m_s', label: '时分秒' }, // 没有同环比
                  { value: 'y_M_d_H_m', label: '年月日时分' },
                  { value: 'y_M_d_H_m_s', label: '年月日时分秒' },
                ],
                control: (val, form) => {
                  console.log('control of dateStyle val=', val)
                  const dict = COMPARE_TYPE_DICT
                  let dicData = []
                  if (val === 'y') {
                    // 年
                    dicData = dict.filter(({ value }) => ['year_mom'].includes(value))
                  } else if (val === 'y_M') {
                    // 年月
                    dicData = dict.filter(({ value }) => ['month_mom', 'year_yoy'].includes(value))
                  } else if (val === 'y_M_d') {
                    // 年月日
                    dicData = dict.filter(({ value }) => ['day_mom', 'month_yoy', 'year_yoy'].includes(value))
                  }

                  return {
                    compareType: { dicData },
                  }
                },
                span: 24,
              },
            ],
          },
        ],
      },
      dimensions: [],
      quotas: [],
    }
  },
  computed: {
    filterDimensions() {
      return this.dimensions.filter((item) => this.form.dimension.includes(item.id))
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.init()
      }
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      const form = await this.loadConfig(this.$route.query.id)
      if (form && form.id) {
        this.form = form
      } else {
        this.form = INIT_FORM()
      }
    },
    getValue() {
      const form = this.form

      const yaxis = this.quotas
        .filter((item) => item.id === form.field)
        .map((item) => ({
          ...item,
          disabled: true,
          compareCalc: {
            type: form.cate === 'DI' ? form.compareType : 'none',
            resultData: 'percent',
            field: form.dateDimension,
            custom: {
              field: '',
              calcType: '0',
              timeType: '0',
              currentTime: '',
              compareTime: '',
              currentTimeRange: [],
              compareTimeRange: [],
            },
          },
          formatterCfg: {
            type: form.formatterCfg.type || 'auto',
            unit: form.formatterCfg.unit || 1,
            suffix: form.formatterCfg.suffix || '',
            decimalCount: form.formatterCfg.decimalCount || 2,
            thousandSeparator: form.formatterCfg.thousandSeparator || true,
          },
          chartType: 'line',
          summary: form.summary || 'sum',
          sort: 'none',
          filter: [],
        }))
      const xaxis = this.dimensions
        .filter((item) => item.id === (form.dateDimension ? form.dateDimension : form.dimension[0]))
        .map((item) => ({
          ...item,
          disabled: true,
          formatterCfg: {
            type: 'auto',
            unit: 1,
            suffix: '',
            decimalCount: 2,
            thousandSeparator: true,
          },
          dateStyle: item.id === form.dateDimension ? form.dateStyle || 'y_M_d' : '',
          datePattern: 'date_sub',
          sort: 'none',
          filter: [],
        }))

      return {
        tableId: this.form.tableId,
        xaxis: xaxis,
        yaxis: yaxis,
        filters: this.form.filters,
        config: {
          ...this.form,
          dimensions: this.dimensions,
          // .map((item) => ({
          //   id: item.id,
          //   name: item.name,
          // })),
        },
      }
    },
    validate(callback) {
      this.$refs.form.validate(callback)
    },
    async onTableIdChange({ value }) {
      console.log('onTableIdChange value=', value)

      if (!value) {
        return
      }

      try {
        const { success, data } = await getDatasetFieldListFromDE({ id: value })
        if (success) {
          this.quotas = data.quota
          this.dimensions = data.dimension

          const dicData = data.quota.map((item) => ({
            id: item.id,
            name: item.name,
          }))
          this.$refs.form && this.$refs.form.updateDic('field', dicData)

          const dimensions = data.dimension.map((item) => ({
            id: item.id,
            name: item.name,
          }))
          this.$refs.form && this.$refs.form.updateDic('dimension', dimensions)
          this.$refs.form && this.$refs.form.updateDic('dateDimension', dimensions)
        }
      } catch (error) {
        console.log('getDatasetFieldListFromDE error=', error)
      }
    },
    onFormatChange(payload) {
      console.log('onFormatChange, payload=', payload)
      this.form.formatterCfg = payload
    },
    onFilterChange(payload) {
      console.log('onFilterChange, payload=', payload)
      const filters = []
      for (let i = 0; i < payload.length; i++) {
        const list = this.dimensions.filter((item) => item.id === payload[i].fieldId)
        if (list.length > 0) {
          filters.push({
            ...list[0],
            disabled: false,
            filter: [
              {
                fieldId: payload[i].fieldId,
                term: payload[i].term,
                value: payload[i].value,
              },
            ],
            index: i,
            logic: 'and',
            filterType: 'logic',
            enumCheckField: [],
          })
        }
      }

      this.form.filters = filters
    },
    async loadConfig(matrixId) {
      try {
        const { success, data } = await requestMatrixOriginGet(matrixId)
        if (success) {
          return data
        }
      } catch (error) {
        console.log(error)
      }

      return {}
    },
    async onFromChartChange({ value, item }) {
      console.log('onFromChartChange value=', value, 'item=', item)
      if (!value) {
        return
      }

      const form = await this.loadConfig(value)
      this.$set(this.form, 'tableId', form.tableId)
      this.form.field = form.field
      this.form.summary = form.summary
      this.form.formatterCfg = form.formatterCfg
      this.form.dimension = form.dimension
      this.form.filters = form.filters
      this.form.dateDimension = form.dateDimension
      this.form.dateStyle = form.dateStyle
    },
  },
}
</script>
<style lang="scss">
.maxtrix-design-form {
  .svg-icon {
    font-size: 20px;
    margin-right: 8px;
  }
}
</style>
